package com.izhang3.proxy.check;

import com.alibaba.fastjson.JSON;
import com.izhang3.proxy.channel.ChannelService;
import com.izhang3.proxy.config.ChannelTypeEnum;
import com.izhang3.proxy.utils.ProxyIpCheckUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 张良
 * @desc
 * @since 2019/6/20 14:33
 */
@Component
public class IpCheckService {

    private static Logger logger = LoggerFactory.getLogger(IpCheckService.class);

    @Autowired
    private ChannelService channelService;

    /**
     * 检查代理IP是否有效
     */
    public void check(ChannelTypeEnum type) {
        logger.info("begin 检查代理IP有效性 type={}", type.name());
        List<String> list = channelService.getWaitList(type);
        //过滤掉无效的IP地址
        list = list.stream().filter(a -> ProxyIpCheckUtils.checkIpProxy(a))
                .collect(Collectors.toList());
        logger.info("end 检查代理IP有效性 type={} result={}", type.name(), JSON.toJSONString(list));
        if (!CollectionUtils.isEmpty(list)) {
            channelService.addWaitList(list, ChannelTypeEnum.CHECK);
        }
    }
}
